/*
* 路由
*
*/

import nProgress from "nprogress"; // 进度条
import 'nprogress/nprogress.css';
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router';
import { routerArray } from './routers';
import { PAGE_PATH_LOGIN, PAGE_PATH_404 } from '@/constants/common-const';
import { HOME_PAGE_PATH } from '@/constants/system/home-const';
import { localClear } from '@/utils/local-util';
import { useUserStore } from '@/store/system/user';
import { sessionClear } from '@/utils/session-util';
import { ElMessage } from 'element-plus';

export const router = createRouter({
    history: createWebHistory(),     // history 模式
    // history: createWebHashHistory(),    // hash 模式
    routes: routerArray,
    strict: true, // 适用所有路由
    scrollBehavior: () => ({ left: 0, top: 0 }), // 滚动行为
});

// 检查路由是否存在
function routeExists(path, router) {
    return router.hasRoute(path) || router.getRoutes().some(route => route.path === path);
}

// ========================= 路由加载前 =========================
router.beforeEach((to, from, next) => {
    // 开启进度条
    nProgress.start(); 
    // 公共页面任何时候都可以跳转
    // 验证路由
    if(!routeExists(to.path, router)) {
        next(PAGE_PATH_404);
        return;
    };
    // 验证登录
    const token = useUserStore().token;
    if(to.path == '/user') {
        if(!token) {
            ElMessage.error('您还没有登录，请先进行登录')
            next({
                path: PAGE_PATH_LOGIN
            });
            return;
        }
    };
    next();
});

// ========================= 路由加载后 =========================
router.afterEach(() => {
    nProgress.done();
});